// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using IdentityServer4.Configuration;
using System.Linq;
using System;
using System.Text.RegularExpressions;

#pragma warning disable 1591

namespace IdentityServer4.Hosting
{
    public class BaseUrlMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IdentityServerOptions _options;

        public BaseUrlMiddleware(RequestDelegate next, IdentityServerOptions options)
        {
            _next = next;
            _options = options;
        }

        public async Task Invoke(HttpContext context)
        {
            var request = context.Request;

            if (_options.PublicOrigin.IsPresent())
            {
                var reg = new Regex(@"(https?)://(\w+\..*?\.com)(/?.*)");
                var uris = reg.Replace(_options.PublicOrigin, "$1,$2,$3").Split(',');

                request.Scheme = uris.First();
                request.Host = new HostString(uris.Skip(1).First());

                if (uris[2].IsPresent())
                {
                    context.Request.PathBase = uris[2];
                }
            }

            var origin = request.Scheme + "://" + request.Host.Value;
            context.SetIdentityServerOrigin(origin);
            context.SetIdentityServerBasePath(request.PathBase.Value.RemoveTrailingSlash());


            await _next(context);
        }
    }
}